<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 御宅男 <530765310@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 模型模型
// +----------------------------------------------------------------------
namespace app\admin\model\cms;

use app\common\model\Modelbase;
use think\Db;
use think\Exception;
use think\facade\Cache;
use think\facade\Config;
use think\Model;

/**
 * 模型
 */
class Models extends Modelbase
{

    protected $name               = 'model';
    protected $autoWriteTimestamp = true;

    protected static $ext_table = '_data';

    protected static function init()
    {
        //添加
        self::beforeInsert(function ($row) {
            $setting['category_template'] = $row->category_template;
            $setting['list_template']     = $row->list_template;
            $setting['show_template']     = $row->show_template;
            $row['setting']               = serialize($setting);
            $row['module']                = 'cms';
            $info                         = null;
            try {
                $info = Db::name($row['tablename'])->getPk();
            } catch (\Exception $e) {
            }
            if ($info) {
                throw new Exception("数据表已经存在");
            }
        });
        self::afterInsert(function ($row) {
            cache::set("Model", null);
            cache::set('ModelField', null);
            //创建模型表和模型字段
            if (self::createTable($row)) {
                self::addFieldRecord($row['id'], $row['type']);
            }
        });
        //编辑
        self::beforeUpdate(function ($row) {
            $changedData = $row->getChangedData();
            $setting     = [];
            if (isset($changedData['category_template'])) {
                $setting['category_template'] = $row->category_template;
            }
            if (isset($changedData['list_template'])) {
                $setting['list_template'] = $row->list_template;
            }
            if (isset($changedData['show_template'])) {
                $setting['show_template'] = $row->show_template;
            }
            if ($setting) {
                $row['setting'] = serialize($setting);
            }
            if (isset($changedData['tablename'])) {
                $info = null;
                try {
                    $info = Db::name($row['tablename'])->getPk();
                } catch (\Exception $e) {
                }
                if ($info) {
                    throw new Exception("数据表已经存在");
                }
                try {
                    $info = Db::name($row['tablename'] . self::$ext_table)->getPk();
                } catch (\Exception $e) {
                }
                if ($info) {
                    throw new Exception("数据表已经存在");
                }
            }
        });
        self::afterUpdate(function ($row) {
            //更新缓存
            cache::set("Model", null);
            cache::set('ModelField', null);
            Cache::set('getModel_' . $row['id'], '');
            $changedData = $row->getChangedData();
            if (isset($changedData['tablename'])) {
                //表前缀
                $dbPrefix = Config::get("database.prefix");
                //表名更改
                Db::execute("RENAME TABLE  `{$dbPrefix}{$row->getOrigin('tablename')}` TO  `{$dbPrefix}{$changedData['tablename']}` ;");
                //修改副表
                if ($row['type'] == 2) {
                    Db::execute("RENAME TABLE  `{$dbPrefix}{$row->getOrigin('tablename')}_data` TO  `{$dbPrefix}{$changedData['tablename']}_data` ;");
                }
            }
        });
        //删除
        self::beforeDelete(function ($row) {
            $exist = Category::where('modelid', $row['id'])->find();
            if ($exist) {
                throw new Exception("该模型使用中，删除栏目后再删除！");
            }
        });
        self::afterDelete(function ($row) {
            cache::set("Model", null);
            cache::set('ModelField', null);
            //删除所有和这个模型相关的字段
            Db::name("ModelField")->where("modelid", $row['id'])->delete();
            //删除主表
            $table_name = Config::get("database.prefix") . $row['tablename'];
            Db::execute("DROP TABLE IF EXISTS `{$table_name}`");
            if ((int) $row['type'] == 2) {
                //删除副表
                $table_name .= self::$ext_table;
                Db::execute("DROP TABLE IF EXISTS `{$table_name}`");
            }
        });
    }

    public function getSettingAttr($value, $data)
    {
        return unserialize($value);
    }

    /**
     * 创建内容模型
     */
    public static function createTable($data)
    {
        $data['tablename'] = strtolower($data['tablename']);
        $table             = Config::get("database.prefix") . $data['tablename'];
        $sql               = <<<EOF
                CREATE TABLE `{$table}` (
                `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT '文档ID',
                `catid` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '栏目ID',
                `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '标题',
                `thumb` varchar(255) NOT NULL DEFAULT '' COMMENT '缩略图',
                `flag` varchar(32) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '属性',
                `keywords` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'SEO关键词',
                `description` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'SEO描述',
                `tags` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'Tags标签',
                `listorder` smallint(5) unsigned NOT NULL DEFAULT '100' COMMENT '排序',
                `uid` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT '用户id',
                `username` varchar(20) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '用户名',
                `sysadd` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '是否后台添加',
                `hits` mediumint(8) UNSIGNED DEFAULT 0 COMMENT '点击量' ,
                `inputtime` int(10) unsigned NOT NULL DEFAULT '0'  COMMENT '创建时间',
                `updatetime` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',
                `url` varchar(100) NOT NULL DEFAULT '' COMMENT '链接地址',
                `status` tinyint(2) NOT NULL DEFAULT '0' COMMENT '状态',
                PRIMARY KEY (`id`),
                KEY `status` (`catid`,`status`)
                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='{$data['name']}模型表';
EOF;

        $res = Db::execute($sql);
        if ($data['type'] == 2) {
            $table = $table . self::$ext_table;
            // 新建附属表
            $sql = <<<EOF
                CREATE TABLE `{$table}` (
                `did` mediumint(8) unsigned NOT NULL DEFAULT '0',
                `content` mediumtext COLLATE utf8_unicode_ci COMMENT '内容',
                PRIMARY KEY (`did`)
                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='{$data['name']}模型表';
EOF;
            $res = Db::execute($sql);
        }
        return true;
    }

    /**
     * 添加默认字段
     */
    public static function addFieldRecord($modelid, $type)
    {
        $fieldsArr = [];
        $default   = [
            'modelid'     => $modelid,
            'pattern'     => '',
            'errortips'   => '',
            'create_time' => time(),
            'update_time' => time(),
            'ifsystem'    => 1,
            'status'      => 1,
            'listorder'   => 100,
            'ifsearch'    => 0,
            'iffixed'     => 1,
            'remark'      => '',
            'isadd'       => 0,
            'iscore'      => 0,
            'ifrequire'   => 0,
            'setting'     => null,
        ];
        $data = [
            [
                'name'  => 'id',
                'title' => '文档id',
                'type'  => 'hidden',
                'isadd' => 1,
            ],
            [
                'name'  => 'catid',
                'title' => '栏目id',
                'type'  => 'hidden',
                'isadd' => 1,
            ],
            [
                'name'   => 'uid',
                'title'  => '用户id',
                'type'   => 'number',
                'iscore' => 1,
            ],
            [
                'name'   => 'username',
                'title'  => '用户名',
                'type'   => 'text',
                'iscore' => 1,
            ],
            [
                'name'   => 'sysadd',
                'title'  => '是否后台添加',
                'type'   => 'number',
                'iscore' => 1,
            ],
            [
                'name'      => 'title',
                'title'     => '标题',
                'type'      => 'text',
                'ifsearch'  => 1,
                'ifrequire' => 1,
                'setting'   => "a:3:{s:6:\"define\";s:32:\"varchar(255) NOT NULL DEFAULT ''\";s:7:\"options\";s:0:\"\";s:5:\"value\";s:0:\"\";}",
                'isadd'     => 1,
                'listorder' => 300,
            ],
            [
                'name'      => 'flag',
                'title'     => '属性',
                'type'      => 'checkbox',
                'setting'   => "a:3:{s:6:\"define\";s:31:\"varchar(32) NOT NULL DEFAULT ''\";s:7:\"options\";s:76:\"1:置顶[1]\r\n2:头条[2]\r\n3:特荐[3]\r\n4:推荐[4]\r\n5:热点[5]\r\n6:幻灯[6]\";s:5:\"value\";s:0:\"\";}",
                'listorder' => 295,
            ],
            [
                'name'      => 'keywords',
                'title'     => 'SEO关键词',
                'type'      => 'tags',
                'iffixed'   => 0,
                'remark'    => '关键词用回车确认',
                'setting'   => "a:3:{s:6:\"define\";s:32:\"varchar(255) NOT NULL DEFAULT ''\";s:7:\"options\";s:0:\"\";s:5:\"value\";s:0:\"\";}",
                'isadd'     => 1,
                'listorder' => 290,
            ],
            [
                'name'      => 'description',
                'title'     => 'SEO摘要',
                'type'      => 'textarea',
                'iffixed'   => 0,
                'remark'    => '如不填写，则自动截取附表中编辑器的200字符',
                'setting'   => "a:3:{s:6:\"define\";s:32:\"varchar(255) NOT NULL DEFAULT ''\";s:7:\"options\";s:0:\"\";s:5:\"value\";s:0:\"\";}",
                'isadd'     => 1,
                'listorder' => 285,
            ],
            [
                'name'      => 'tags',
                'title'     => 'Tags标签',
                'type'      => 'tags',
                'iffixed'   => 0,
                'remark'    => '关键词用回车确认',
                'setting'   => "a:3:{s:6:\"define\";s:32:\"varchar(255) NOT NULL DEFAULT ''\";s:7:\"options\";s:0:\"\";s:5:\"value\";s:0:\"\";}",
                'listorder' => 280,
            ],
            [
                'name'      => 'thumb',
                'title'     => '缩略图',
                'type'      => 'image',
                'ifrequire' => 0,
                'iffixed'   => 0,
                'setting'   => "a:3:{s:6:\"define\";s:13:\"text NOT NULL\";s:7:\"options\";s:0:\"\";s:5:\"value\";s:0:\"\";}",
                'isadd'     => 1,
                'listorder' => 275,
            ],
            [
                'name'      => 'hits',
                'title'     => '点击量',
                'type'      => 'number',
                'listorder' => 265,
                'setting'   => "a:3:{s:6:\"define\";s:42:\"mediumint(8) UNSIGNED NOT NULL DEFAULT '0'\";s:7:\"options\";s:0:\"\";s:5:\"value\";s:1:\"0\";}",
            ],
            [
                'name'      => 'listorder',
                'title'     => '排序',
                'type'      => 'number',
                'setting'   => "a:3:{s:6:\"define\";s:40:\"tinyint(3) UNSIGNED NOT NULL DEFAULT '0'\";s:7:\"options\";s:0:\"\";s:5:\"value\";s:3:\"100\";}",
                'listorder' => 260,
            ],
            [
                'name'      => 'url',
                'title'     => '链接地址',
                'type'      => 'text',
                'listorder' => 255,
                'setting'   => "a:3:{s:6:\"define\";s:32:\"varchar(100) NOT NULL DEFAULT ''\";s:7:\"options\";s:0:\"\";s:5:\"value\";s:0:\"\";}",
                'remark'    => '有值时生效，内部链接格式:模块/控制器/操作?参数=参数值&...，外部链接则必须http://开头',
            ],
            [
                'name'      => 'inputtime',
                'title'     => '创建时间',
                'type'      => 'datetime',
                'listorder' => 250,
                'setting'   => "a:3:{s:6:\"define\";s:37:\"int(10) UNSIGNED NOT NULL DEFAULT '0'\";s:7:\"options\";s:0:\"\";s:5:\"value\";s:0:\"\";}",
            ],
            [
                'name'      => 'updatetime',
                'title'     => '更新时间',
                'type'      => 'datetime',
                'listorder' => 245,
                'setting'   => "a:3:{s:6:\"define\";s:37:\"int(10) UNSIGNED NOT NULL DEFAULT '0'\";s:7:\"options\";s:0:\"\";s:5:\"value\";s:0:\"\";}",
                'iscore'    => 1,
            ],
            [
                'name'      => 'status',
                'title'     => '状态',
                'type'      => 'radio',
                'setting'   => "a:3:{s:6:\"define\";s:40:\"tinyint(2) UNSIGNED NOT NULL DEFAULT '0'\";s:7:\"options\";s:18:\"0:禁用\r\n1:启用\";s:5:\"value\";s:1:\"1\";}",
                'listorder' => 240,
            ],
        ];
        if ($type == 2) {
            array_push($data, [
                'name'     => 'did',
                'title'    => '附表文档id',
                'type'     => 'hidden',
                'iscore'   => 1,
                'ifsystem' => 0,
            ],
                [
                    'name'      => 'content',
                    'title'     => '内容',
                    'type'      => 'Ueditor',
                    'ifsystem'  => 0,
                    'iffixed'   => 0,
                    'setting'   => "a:3:{s:6:\"define\";s:13:\"text NOT NULL\";s:7:\"options\";s:0:\"\";s:5:\"value\";s:0:\"\";}",
                    'isadd'     => 1,
                    'listorder' => 270,
                ]);

        }
        foreach ($data as $item) {
            $fieldsArr[] = array_merge($default, $item);
            //Db::name('model_field')->insert($item);
        }
        Db::name('model_field')->insertAll($fieldsArr);
        return true;
    }

}
